//
//  UPRepaymentCarouselView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/24.
//

#import "UPGoToApplyCarouselView.h"
#import "UPGoToApplyCarouseCell.h"
#import <Masonry/Masonry.h>

@interface UPGoToApplyCarouselView () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) NSArray<StultiiveModel *> *dataSources;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;

@end

@implementation UPGoToApplyCarouselView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commontInitSubViews];
    }
    return self;
}

- (void)updateWithDatas:(NSArray<StultiiveModel *> *)datas {
    self.dataSources = datas;
    [self.collectionView reloadData];
    [self updateSubviews];
}

- (void)setDatas:(NSArray<StultiiveModel *> *)datas {
    self.dataSources = datas;
    self.pageControl.numberOfPages = datas.count;
    [self.collectionView reloadData];
    
    // 重置位置
    NSInteger middleIndex = datas.count * 100;
    if ([self.collectionView numberOfItemsInSection:0] > middleIndex) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:middleIndex inSection:0]
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                            animated:NO];
    }
}

- (void)commontInitSubViews {
    // 配置collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[UPGoToApplyCarouseCell class] forCellWithReuseIdentifier:@"UPRepaymentCarouseCell"];
    [self addSubview:self.collectionView];
    
    self.pageControl = [[UIPageControl alloc] init];
    self.pageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:@"#F9D14B"];
    self.pageControl.pageIndicatorTintColor = [[UIColor colorWithHexString:@"#000000"] colorWithAlphaComponent:0.66];
    self.pageControl.hidden = YES;
    [self addSubview:self.pageControl];
}

- (void)updateSubviews {
    if (self.dataSources.count == 0) return;
    
    // 配置pageControl
    self.pageControl.numberOfPages = self.dataSources.count;
    
    // 开始自动轮播
    [self startAutoScroll];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.collectionView.frame = self.bounds;
    
    CGFloat pageControlHeight = 30;
    self.pageControl.frame = CGRectMake(0,
                                      self.bounds.size.height - pageControlHeight,
                                      self.bounds.size.width,
                                      pageControlHeight);
    
    // 初始位置设置为中间位置，实现无限轮播
    NSInteger middleIndex = self.dataSources.count * 100;
    if ([self.collectionView numberOfItemsInSection:0] > middleIndex) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:middleIndex inSection:0]
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                            animated:NO];
    }
}

#pragma mark - Auto Scroll

- (void)startAutoScroll {
    [self.timer invalidate];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                                 target:self
                                               selector:@selector(autoScroll)
                                               userInfo:nil
                                                repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)autoScroll {
//    NSInteger nextIndex = self.currentIndex + 1;
//    [self scrollToIndex:nextIndex];
}

- (void)scrollToIndex: (NSInteger) nextIndex {
    if (self.dataSources.count <= 1) return;
    NSInteger middleIndex = self.dataSources.count * 100;
    if ([self.collectionView numberOfItemsInSection:0] > nextIndex) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:nextIndex inSection:0]
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                            animated:YES];
    }
    
    // 如果接近边界，重置到中间位置
    if (nextIndex > middleIndex + self.dataSources.count - 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if ([self.collectionView numberOfItemsInSection:0] > middleIndex) {
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:middleIndex inSection:0]
                                            atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                                    animated:NO];
            }
        });
    }
}

- (void)stopAutoScroll {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)dealloc {
    [self stopAutoScroll];
}

#pragma mark - UICollectionViewDataSource & UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSources.count == 0 ? 0 : self.dataSources.count * 200;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UPGoToApplyCarouseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UPRepaymentCarouseCell" forIndexPath:indexPath];
    NSInteger index = indexPath.item % self.dataSources.count;
    StultiiveModel *stultiiveModel = self.dataSources[index];
    cell.stultiiveModel = stultiiveModel;

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.bounds.size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger index = indexPath.item % self.dataSources.count;
    StultiiveModel *stultiiveModel = self.dataSources[index];
    if ([self.delegate respondsToSelector:@selector(carouselView:didSelectItemAtIndex:data:)]) {
        [self.delegate carouselView:self didSelectItemAtIndex:index data:stultiiveModel];
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.dataSources.count == 0) return;
    
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger currentPage = (NSInteger)((scrollView.contentOffset.x + pageWidth / 2) / pageWidth) % self.dataSources.count;
    self.pageControl.currentPage = currentPage;
    self.currentIndex = (NSInteger)(scrollView.contentOffset.x / pageWidth);
    
    if (currentPage < self.dataSources.count) {
        if ([self.delegate respondsToSelector:@selector(carouselView: didScrollToIndex: data:)]) {
            [self.delegate carouselView:self didScrollToIndex:currentPage data:self.dataSources[currentPage]];
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopAutoScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startAutoScroll];
}

#pragma mark - UPRepaymentCarouseCellDelegate

- (void)didClickRepaymentButtonWithData:(LeaderibleModel *)data {
    // 处理还款按钮点击事件
}

@end
